package sqlib;
import java.lang.reflect.Field;


public  class SQLGenerator {

	private DataMapper mapper;
	
	public SQLGenerator(DataMapper mapper) {
		this.mapper = mapper;
	}
	
	public void setMapper(DataMapper mapper) {
		this.mapper = mapper;
	}
	public String createTableInstruction(Class<?> c) {
		String sql = "CREATE TABLE " + c.getSimpleName() + "(";
		Field[] fields = c.getDeclaredFields();
		
		for(int i = 0; i < fields.length; i++) {
			if(i != 0)
				sql += ",";
			sql += fields[i].getName() + " " + mapper.convertType(fields[i].getType());
			
		}
		sql += ");";
		return sql;
	}
	
	
//	private String convertType(Class<?> type) {
//		if(type.equals(String.class))
//			return "VARCHAR";
//		else if(type.equals(int.class))
//			return "INT";
//		else if(type.equals(boolean.class))
//			return "BIT";
//			
//		throw new RuntimeException("type not supported - " + type);
//	}

	public String createInsertStatement(Object object) {
		Class<?> c = object.getClass();
		String sql = "INSERT INTO " + c.getSimpleName() + " VALUES (";
		Field[] fields = c.getDeclaredFields();
		
		for(int i = 0; i < fields.length; i++) {
			if(i != 0)
				sql += ",";
			try {
				fields[i].setAccessible(true);
				Object obj = fields[i].get(object);	
				sql += convertToSQL(obj);
				
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		sql += ");";
		return sql;
	}

	private String convertToSQL(Object obj) {
		if(obj.getClass().equals(String.class))
			return "'" + obj.toString() + "'";
		
		return obj.toString();
	}
}
